package com.kcs.fxmargin.service;

import java.math.BigDecimal;
import java.sql.Connection;
import java.util.Calendar;
import java.util.Locale;

import th.co.kcs.www.schema.CBS.InquiryAccountDetailRequestType;
import th.co.kcs.www.schema.CBS.InquiryAccountDetailResponseType;
import th.co.kcs.www.schema.CBS.InquiryAccountStatementRequestType;
import th.co.kcs.www.schema.CBS.InquiryAccountStatementResponseType;
import th.co.kcs.www.schema.CBS.InquiryAccountStatementResponseTypeInquiryAccountStatementRespData;
import th.co.kcs.www.schema.CBS.RequestHeaderType;
import th.co.kcs.www.wsdl.AccountServices.AccountServicesPortTypeProxy;

import com.kcs.common.utils.ConnectionUtils;
import com.kcs.common.utils.Constant;
import com.kcs.fxmargin.bo.CheckLimitOrderBO;
import com.kcs.fxmargin.dao.CheckLimitOrderDAO;

public class CheckLimitOrderService {
	public CheckLimitOrderBO checkLimit(CheckLimitOrderBO bo)throws Exception{
		Connection connOra = null;
		Connection conn = null;
		CheckLimitOrderDAO dao = null;
		boolean result = false;
		
		try{
			
			if(validateCheckLimit(bo)){
			
				//-- Get Data from RETAD
				connOra = ConnectionUtils.getConnection(Constant.ORACLE, Constant.FROM);
				dao = new CheckLimitOrderDAO();
				bo = dao.getTDealsDataFromRETAD(bo, connOra);
				connOra.close();
				
				if(bo.gettDealsList() != null){
					//-- Delete TDeals FX Margin
					conn = ConnectionUtils.getConnection(Constant.MSSQL, Constant.TO);

					result = dao.deleteTDeals(bo, conn);
					System.out.println("Delete TDeals success!");
					
					//-- Insert TDeals FX Margin
					dao.insertTDeals(bo, conn);
					System.out.println("Insert TDeals success!");
					
					//-- Get t_pre_order
					bo = dao.getPreOrderAmount(bo, conn);
					System.out.println("Get preOrderAmount : "+bo.getPreOrderAmount());
					
					//-- Get m_cust_info
					bo = dao.getMCustInfo(bo, conn);
					System.out.println("Get MCustInfo : "+bo.getmCustInfo());
					if(bo.getmCustInfo() != null){
						bo.setCustLimitAvailable(bo.getmCustInfo().getCustLimitAmt().toString());
					}
					
					//-- Call WS InquiryAccountDetail
					bo = inquiryAccountDetail(bo);
					System.out.println("Call WS inquiryAccountDetail : "+bo.getOutsBal());
					
					//-- Check t_acc_pos
					bo = dao.getTAccPos(bo, conn);
					System.out.println("Check TAccPos : "+bo.gettAccPos());
					if(bo.gettAccPos() != null){
						dao.updateTAccPos(bo,conn);
						System.out.println("Update TAccPos success!");
					}else{
						dao.insertTAccPos(bo,conn);
						System.out.println("Insert TAccPos success!");
					}
					
					//-- Call WS InquiryAccountStatement //***
					//bo = inquiryAccountStatement(bo);
					//System.out.println("Call WS InquiryAccountStatement : ***");
					
					//-- Check t_acc_tran
					bo = dao.getTAccTrans(bo, conn);
					System.out.println("Check TAccTrans : "+bo.gettAccTran());
					if(bo.gettAccTran() == null){
						dao.insertTAccTran(bo, conn);
						System.out.println("Insert TAccTran success!");
					}
					
					//-- Call SPCalMarginLimit
					bo = dao.callMarginLimit(bo, conn);
					bo.setFxLimitAvailable(bo.getMarginLimit());
					System.out.println("Call SPCalMarginLimit : "+bo.getFxLimitAvailable());
				}
				
				conn.commit();
				result =  true;
				
				
			}else{
				throw new Exception(Constant.ERR_CIF_NO_EMPTY);
			}
			
			bo.setProcessSuccess(result);
			
		}catch(Exception e){
			if(conn != null){
				try{
					conn.rollback();
				}catch(Exception ex){
					throw ex;
				}
			}
				
			throw e;
		}finally{
			if(connOra != null){
				try{
					connOra.close();
				}catch(Exception ex){
					throw ex;
				}
			}
			if(conn != null){
				try{
					conn.close();
				}catch(Exception ex){
					throw ex;
				}
			}
		}
		
		return bo;
		
	}
	
	private boolean validateCheckLimit(CheckLimitOrderBO bo){
		return !bo.getInCifNo().equals("");
	}
	
	private String getYYYYMMDDToday(){
		Locale locale = new Locale("us","US");
		Calendar c = Calendar.getInstance(locale);
		int y = c.get(Calendar.YEAR);
		int m = c.get(Calendar.MONTH);
		int d = c.get(Calendar.DATE);
		
		return (y+"") + (m<10?"0"+m:m+"") + (d<10?"0"+d:d+"");
	}
	
	private String getHHMMSSNow(){
		Locale locale = new Locale("us","US");
		Calendar c = Calendar.getInstance(locale);
		int h = c.get(Calendar.HOUR);
		int m = c.get(Calendar.MINUTE);
		int s = c.get(Calendar.SECOND);
		
		return (h<10?"0"+h:h+"") + (m<10?"0"+m:m+"") + (s<10?"0"+s:s+"");
	}
	
	private CheckLimitOrderBO inquiryAccountDetail(CheckLimitOrderBO bo)throws Exception{
		AccountServicesPortTypeProxy proxy = null;
		InquiryAccountDetailRequestType request = null;
		InquiryAccountDetailResponseType response = null;
		RequestHeaderType header = null;
		String channelId = null;
		String tranDate = null;
		String transTime = null;
		int refId = 0;
		String acctId = null;
		
		try{
			channelId = "FX";
			tranDate = getYYYYMMDDToday();
			transTime = getHHMMSSNow();
			refId = Integer.parseInt(bo.getInCifNo());
			acctId = bo.getmCustInfo().getMarginAccNo();
			
			header = new RequestHeaderType(channelId, tranDate, transTime, refId);

			request = new InquiryAccountDetailRequestType(header,acctId);
			
			proxy = new AccountServicesPortTypeProxy();
			
			response = proxy.inquiryAccountDetail(request);
			
			bo.setOutsBal(response.getOutsBal());
			
			
		}catch(Exception e){
			throw e;
		}
		
		
		return bo;
	}
	
	private CheckLimitOrderBO inquiryAccountStatement(CheckLimitOrderBO bo)throws Exception{
		AccountServicesPortTypeProxy proxy = null;
		InquiryAccountStatementRequestType request = null;
		InquiryAccountStatementResponseType response = null;
	    InquiryAccountStatementResponseTypeInquiryAccountStatementRespData data = null;
		RequestHeaderType header = null;
		String channelId = null;
		String tranDate = null;
		String transTime = null;
		int refId = 0;
		String acctId = null;
		String rangeStartDt = null;
		String rangeEndDt = null;
		BigDecimal rangeStartTransAmt = null;
		BigDecimal rangeEndTransAmt = null;
		String lastAcctId = null;
		Integer lastSeq = null;
		
		try{

			channelId = "FX";
			tranDate = getYYYYMMDDToday();
			transTime = getHHMMSSNow();
			refId = Integer.parseInt(bo.getInCifNo());
			acctId = bo.getmCustInfo().getMarginAccNo();
			rangeStartDt = getYYYYMMDDToday();
			rangeEndDt = getYYYYMMDDToday();
			rangeStartTransAmt = new BigDecimal(0);
			rangeEndTransAmt = new BigDecimal(9999999999.99);
			lastAcctId = "0";
			lastSeq = new Integer(0);
			
			header = new RequestHeaderType(channelId, tranDate, transTime, refId);
			
			request = new InquiryAccountStatementRequestType(header,acctId,rangeStartDt,rangeEndDt,rangeStartTransAmt,rangeEndTransAmt,lastAcctId,lastSeq);
			
			proxy = new AccountServicesPortTypeProxy();
			
			response = proxy.inquiryAccountStatement(request);
			
			data = response.getInquiryAccountStatementRespData();
			
			//***
			bo.setDrCrFlg(null);
			bo.setTransAmt(null);
			bo.setTransRefNo(null);
			bo.setTransDt(null);
			bo.setTransTime("");
			bo.setEffDt(null);
			bo.setSeq("");
			
		}catch(Exception e){
			throw e;
		}
		
		
		return bo;
	}
	
}
